package com.education.platform.websocket;

import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * WebSocket握手拦截器
 *
 * @author education-platform
 * @since 2024-10-07
 */
@Component
@Slf4j
public class WebSocketInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        
        String uri = request.getURI().toString();
        log.info("WebSocket握手请求: {}", uri);
        
        try {
            // 从请求参数中获取token
            String query = request.getURI().getQuery();
            String token = null;
            
            if (query != null && query.contains("token=")) {
                String[] params = query.split("&");
                for (String param : params) {
                    if (param.startsWith("token=")) {
                        token = param.substring(6);
                        break;
                    }
                }
            }
            
            if (token == null || token.isEmpty()) {
                log.warn("WebSocket握手失败: 缺少token");
                return false;
            }
            
            // 验证token
            Object loginId = StpUtil.getLoginIdByToken(token);
            if (loginId == null) {
                log.warn("WebSocket握手失败: token无效");
                return false;
            }
            
            // 将用户ID存储到WebSocket会话属性中
            attributes.put("userId", Long.valueOf(loginId.toString()));
            attributes.put("token", token);
            
            log.info("WebSocket握手成功, 用户ID: {}", loginId);
            return true;
            
        } catch (Exception e) {
            log.error("WebSocket握手异常", e);
            return false;
        }
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                               WebSocketHandler wsHandler, Exception exception) {
        if (exception != null) {
            log.error("WebSocket握手后异常", exception);
        }
    }
}
